package com.cat.slidingWindow;

/**
 * @author cat
 * @description https://leetcode.cn/problems/take-k-of-each-character-from-left-and-right/
 * @create 2025/7/30 16:40
 * @since JDK17
 */

public class Solution13 {
    public int takeCharacters(String str, int k) {
        int[] cnt = new int[3];
        int n = str.length(), ans = 0;
        char[] s = str.toCharArray();
        for (int i = 0; i < n; i++) {
            cnt[s[i] - 'a']++;
        }

        if (cnt[0] < k || cnt[1] < k || cnt[2] < k) {
            return -1;
        }
        // 拿走所有的字符
        for (int l = 0, r = 0; r < n; r++) {
            cnt[s[r] - 'a']--;   // 吐出一个字符
            while (cnt[s[r] - 'a'] < k) {    // 拿走的字符不够了
                cnt[s[l++] - 'a']++;  //
            }
            ans = Math.max(ans, r - l + 1);
        }

        return n - ans;
    }
}
